/*!
 * =====================================================
 * datatable v1.0.0 ()
 * jake.xu
 * 18616016103@163.com
 * =====================================================
 */


/******
 * datatbale edit 简单封装
 * 参数相关
 * ********/
(function($, rfq) {
    var defaultDataTableOptions = {
        datatype: 'json',
        url:'',
        mtype:'post',
        initCount:0,
        data:null,
        mappingNames: [],
        cellFormat: null,
        renderDel:true,
        afterLoadData: function () {},
        beforePagination:function () {return true},
        rowNum: 10,
        pageId:'#d_pager',
        sidx:null,
        sord:null
    };
    var delTpl = '<a href="javascript:;" class="js-del"><i class="icon icon-trash red"></i>&nbsp;删除</a><input type="hidden" data-name="id" value="{id}"/>';//删除
    var inputTpl = '<input type="text" class="form-control input-sm" data-name="{name}" value="{value}">';//输入框
    var pageTpl = [ '<ul class="pager pager-loose pagers">',
                    '<li><span>共 <strong class="text-danger" id="_totalCount">{totalCount}</strong> 条记录</span></li>',
                    '<li><span><strong class="text-danger"  id="_pageNum">{page}/{pages}</strong> 页</span></li>',
                    '<li><span>每页显示 <select name="" class="form-control input-sm" id="_pageCount"><option value="10">10</option><option value="20">20</option><option value="30">30</option><option value="50">50</option><option value="100">100</option></select>条</span></li>',
                    '<li> <a href="javascript:;" class="_page" data-index="0">首页</a> </li>',
                    '<li> <a href="javascript:;" class="_page" data-index="1">上一页</a> </li>',
                    '<li> <a href="javascript:;" class="_page" data-index="2">下一页</a> </li>',
                    '<li> <a href="javascript:;" class="_page" data-index="3">尾页</a> </li>',
                    '<li><span>转到 <input type="text" class="form-control input-sm" size="3" id="_toPage">页</span> <span class="ml12"><a class="btn btn-sm" id="_toPageBtn">确定</a></span></li>',
                    '</ul>'].join('');
    var dataTableCache = {};
    rfq.dataTable = function(seletor){
        if(dataTableCache[seletor]){
            return dataTableCache[seletor];
        }
        if(this === rfq){
            return new rfq.dataTable(seletor);
        }
        this.jqObj = $(seletor);
        dataTableCache[seletor] = this;
        return this;
    };
    $.extend(rfq.dataTable.prototype,{
        init: function(options) {
            var that = this;
            options = options||{};
            var newOptions = $.extend({},defaultDataTableOptions,options);
            var dataTable_org = that.jqObj.data('zui.datatable');
            if(!dataTable_org){
                dataTable_org = that.jqObj.datatable({fixedLeftWidth:'50px',fixedHeader:false,}).data('zui.datatable');
            }
            this.options = newOptions;
            this.mappingNames = newOptions.mappingNames;
            this.dataTable_org = dataTable_org;
            this.visibleObj = $('#datatable-'+that.jqObj[0].id);
            this.cols = dataTable_org.data.cols;
            this.rows = dataTable_org.data.rows;
            this.pageEl = $(newOptions.pageId);
            this.lineNum = 1;//序号
            this.totalCount = 0; //总条数
            this.page = 1;//当前页
            this.pages = 1;//总页数
            this.rowNum = newOptions.rowNum;
            this.deleteIds = [];
            this.sidx = newOptions.sidx;
            this.sord = newOptions.sord;
            this.initPage();
            return this;
        },
        initPage: function () {
            var that = this;
            that.pageEl.html(pageTpl.format({totalCount:that.totalCount,page:that.page,pages:that.pages}));
            //分页事件
            var beforePagination = that.options.beforePagination;
            //翻页事件
            that.pageEl.on('click','._page',function () {
                var index = $(this).data('index');
                var toPageNum = 1;
                if(index == 1){//上一页
                    toPageNum = that.page - 1;
                }else if(index == 2){
                    toPageNum = that.page + 1;
                }else if(index == 3){
                    toPageNum = that.pages;
                }
                if(toPageNum <=0 || toPageNum > that.pages){
                    return false;
                }
                if(beforePagination.call(that)){
                    that.page = toPageNum;
                    that.load();
                }
            });

            //页码跳转
            that.pageEl.on('click','#_toPageBtn', function () {
                var $toPage = that.pageEl.find('#_toPage');
                var toPageNum = +$toPage.val();
                !toPageNum && (toPageNum = 1);
                toPageNum = Math.round(toPageNum);
                toPageNum <=0 && (toPageNum = 1);
                toPageNum >that.pages && (toPageNum = that.pages);
                $toPage.val(toPageNum);
                if(beforePagination.call(that)){
                    that.page = toPageNum;
                    that.load();
                }
            });

            //每页显示条数
            that.pageEl.on('change','#_pageCount', function () {
                var _rowNum = that.rowNum;
                if(beforePagination.call(that)){
                    that.rowNum = this.value;
                    //重置页码
                    that.page = 1;
                    that.load();
                }else{
                    this.value = _rowNum;
                }
            });

            //按回车键触发保存
            that.visibleObj.on('keydown','input', function (event) {
                if (event.keyCode == 13) {
                    event.returnValue=false;
                    event.cancel = true;
                    if(beforePagination.call(that)){
                        that.load();
                    }
                }else if(event.keyCode == 9){
                    return false;
                }
            });
        },
        load:function(params,isInit){
            var that = this;
            var datatype = that.options.datatype;
            if(datatype == 'local' || isInit){//本地加载
                that.renderData(that.options.data);
                return;
            }
            params = params||{};
            params.page = that.page;
            params.rows = that.rowNum;
            params.sidx = that.sidx||null;
            params.sord = that.sord||null;


            var searchForm =  that.options.searchForm;
            if(searchForm){
                RFQ.d( $(searchForm).find(':text'));
                $(searchForm).find(':text').each(function () {
                    params[this.name] = this.value;
                });
            }

            var url = that.options.url;
            var mtype = that.options.mtype;
            var process = (mtype=='get'? $.get: $.post);
            process(url,params, function (data) {
                that.pages = Math.max(data.pages,1);
                that.page = Math.max(data.pageNum,1);
                that.totalCount =  data.total;
                that.renderData(data.list||[]);
            },'json');
        },
        clear: function () {
            this.renderData();
        },
        addRow: function () {
            //更新用户手动输入的值
            var that = this;
            that.acceptChanges();
            var rows = that.rows;
            rows.push(that.renderRow());
            that._load(rows);
            that.totalCount++;
            that.updatePage();
        },
        delRow: function (index) {
            var that = this;
            that.acceptChanges();
            var rows = that.rows;
            rows.splice(index,1);
            that._load(rows);
            that.totalCount--;
            that.updatePage();
        },
        acceptChanges: function () {
            var that = this;
            var rows = that.rows;
            var hasDel = that.options.renderDel;
            var ajustIndex = (hasDel?2:1);
            var beginNum = (that.page-1) * (that.rowNum);
            that.visibleObj.find('.flexarea tbody tr').each(function (i1) {
                var data = rows[i1].data;
                $(this).find('input[data-name]').each(function (i2) {
                    var $this = $(this);
                    var name = $this.data('name');
                    if(name != 'id'){
                        var cellFormat = that.options.cellFormat;
                        if(cellFormat){
                            data[i2+ajustIndex] = cellFormat.call(that,name,$this.val(),data,i2);
                        }else{
                            data[i2+ajustIndex] =  inputTpl.format({name:name,value:this.value});
                        }
                    }
                });
            });
        },
        renderData: function (data) {
            var that = this;
            var rows = [];
            if(!data){
                var initCount = that.options.initCount;
                that.totalCount = initCount;
                for(var i=0;i<initCount;i++){
                    rows.push(that.renderRow(i));
                }
            }else{
                //计算序号
                var beginNum = (that.page-1) * (that.rowNum);
                $.each(data, function (i,d) {
                    rows.push(that.renderRow(beginNum+i,d));
                });
            }
            that._load(rows);
            that.updatePage();
        },
        _load: function (rows) {
            var that = this;
            //重置序号
            var beginNum = (that.page-1) * (that.rowNum);
            $.each(rows, function (i,d) {
                d.data[0] = beginNum + i+1;
            });
            that.jqObj.datatable('load',{cols:that.cols,rows:rows});
            that.rows = rows;
            var afterLoadData = that.options.afterLoadData;
            afterLoadData && afterLoadData.call(that,rows);
        },
        renderRow: function (i,data) {
            var that = this;
            data = data||{};
            var cellFormat = this.options.cellFormat;
            var tmp = $.map(that.mappingNames, function(d,index) {
                var rval = '';
                if(cellFormat){
                    rval = cellFormat.call(that, d,data[d]==0?0:data[d]||'',data,index,i);
                }else{
                    rval = inputTpl.format({name:d,value:data[d]||''});
                }
                return rval;
            });
            if(that.options.renderDel){
                tmp.unshift(delTpl.format({id:data['id']||''}));//删除
            }
            tmp.unshift(i === undefined?'':(i+1));//序号
            return {checked: false, data:tmp};
        },
        updatePage: function () {
            var that = this;
            var $pageEl = that.pageEl;
            $pageEl.find('#_totalCount').html(that.totalCount);
            $pageEl.find('#_pageNum').html(that.page + '/' + that.pages);
        },
        fetchChanges: function (preName) {
            var that = this;
            var totalCount = 0;
            var extras = {};
            preName = preName||'';
            that.visibleObj.find('.flexarea tbody tr').each(function(i){
                totalCount = i;
                var $frozenTr = that.visibleObj.find('.fixed-left tbody tr:eq('+i+')');
                var extIndex= 0;
                $(this).find('input[data-name]').each(function (i2) {
                    //TODO 这里与自定义物料耦合了，后期需要重构
                    var tmpName = $(this).data('name');
                    if(~tmpName.indexOf('itemValue_')){//包含代表是自定义物料
                        extras[preName+'['+i+'].itemExtraList['+extIndex+'].itemCode'] = $(this).data('ext');
                        extras[preName+'['+i+'].itemExtraList['+extIndex+'].itemValue'] = this.value;
                        extIndex++;
                    }else{
                        if (tmpName == "tax") {
                            extras[preName+'['+i+'].'+$(this).data('name')] = (""+this.value).replace("%","");
                        }
                        extras[preName+'['+i+'].'+$(this).data('name')] = this.value;
                    }
                });
                $frozenTr.find('input[data-name]').each(function (i2) {
                    extras[preName+'['+i+'].'+$(this).data('name')] = this.value;
                });
            });
            totalCount > 0 && (totalCount ++);
            //删除的
            $.each(that.deleteIds||[], function (i,d) {
                extras[preName+'['+(i+totalCount)+'].id'] = d;
                extras[preName+'['+(i+totalCount)+'].operate'] = 1;
            });
            return extras;
        }
    });
})(window.jQuery, window.RFQ);

